package com.cskaoyan.opensource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建日期: 2022/11/18 11:38
 *
 * @author ciggar
 */
public class DBCPUtils {


    static  DataSource dataSource;

    public static DataSource getDataSource() {
        return dataSource;
    }

    static {

        // 手动构建数据库连接池，手动指定参数
//        BasicDataSource basicDataSource = new BasicDataSource();
//        basicDataSource.setUrl();
//        basicDataSource.setUsername();
//        basicDataSource.setPassword();
//        basicDataSource.setDriverClassName();
//
//        basicDataSource.setInitialSize();
//        basicDataSource.setMinIdle();

        try {
            // 初始化数据库连接池，读取配置文件
            Properties properties = new Properties();
            properties.load(new FileInputStream("dbcp.properties"));
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    // 获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
